package com.ml.ucenterservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ml.commonutils.JwtUtils;
import com.ml.commonutils.Result;
import com.ml.ucenterservice.entity.UcenterMember;
import com.ml.ucenterservice.entity.UcenterMemberCode;
import com.ml.ucenterservice.feign.ContestTableFeignService;
import com.ml.ucenterservice.service.UcenterMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author ShuHaoNan
 * @since 2020-10-26
 */
@RestController
@RequestMapping("/ucenter")
@Api(tags = "用户表")
public class UcenterMemberController {

    @Autowired
    private UcenterMemberService memberService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 远程调用商家比赛表接口
     */
    @Autowired
    private ContestTableFeignService contestTableService;

    /**
     * 密码登录
     */
    @ApiOperation("密码登录")
    @PostMapping("/login")
    public Result loginUser(@RequestBody UcenterMember ucenterMember) {
        // 使用JWT生成token，返回存入Redis中的随机key
        String key = memberService.login(ucenterMember);
        return Result.ok().data("redisTokenKey", key);
    }

    /**
     * 验证码登录
     */
    @ApiOperation("验证码登录")
    @PostMapping("/codeLogin")
    public Result codeLogin(@RequestBody UcenterMemberCode ucenterMemberCode) {
        // 使用JWT生成token，返回存入Redis中的随机key
        String key = memberService.codeLogin(ucenterMemberCode);
        return Result.ok().data("redisTokenKey", key);
    }

    /**
     * 注册
     */
    @ApiOperation("注册")
    @PostMapping("/register")
    public Result registerUser(@RequestBody UcenterMember ucenterMember) {
        memberService.register(ucenterMember);
        return Result.ok();
    }

    /**
     * 根据token获取用户信息
     * @param request
     * @return
     */
    @ApiOperation("根据token获取用户信息")
    @PostMapping("/getMemberInfo")
    public Result getMemberInfo(HttpServletRequest request) {
        String redisToken = request.getParameter("token");
        // 从Redis中查询token
        String JwtToken = (String) redisTemplate.opsForValue().get(redisToken);
        // 调用jwt工具类的方法，根据request对象获取头信息，返回用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(JwtToken);
        // 查询数据库根据用户id获取用户信息
        UcenterMember member = memberService.getById(memberId);
        return Result.ok().data("userInfo", member);
    }

    /**
     * 报名比赛
     *
     * @param memberId 用户ID
     * @param contestId 报名比赛表ID
     * @return
     */
    @ApiOperation("报名比赛")
    @PutMapping("/registerContest/{memberId}/{contestId}")
    public Result registerContest(@PathVariable("memberId") String memberId, @PathVariable("contestId") String contestId) {
        // 修改用户报名状态
        UcenterMember ucenterMember = new UcenterMember();
        ucenterMember.setId(memberId);
        ucenterMember.setIsParameter(contestId);
        memberService.updateById(ucenterMember);
        // 修改比赛表人数
        contestTableService.updateContestTableSigUpIncrease(contestId);
        return Result.ok();
    }

    /**
     * 取消报名
     *
     * @param userInfo 用户信息
     * @return
     */
    @ApiOperation("取消报名")
    @PutMapping("/outRegisterContest")
    public Result outRegisterContest(@RequestBody UcenterMember userInfo) {
        // 修改用户报名状态
        UcenterMember ucenterMember = new UcenterMember();
        ucenterMember.setId(userInfo.getId());
        ucenterMember.setIsParameter("0");
        memberService.updateById(ucenterMember);
        // 修改比赛表人数
        contestTableService.updateContestTableSigUpReduce(userInfo.getIsParameter());
        return Result.ok();
    }

    /**
     * 查询手机号是否注册
     */
    @ApiOperation("查询手机号是否注册")
    @GetMapping("/getMobileIsExist/{mobile}")
    public Result getMobileIsExist(@PathVariable("mobile") String mobile) {
        if (mobile.length() != 11) return Result.error();
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", mobile);
        int result = memberService.count(wrapper);
        // 大于 0 表示存在 否则不存在
        if (result > 0) {
            return Result.error().message("当前手机号已被注册");
        }
        return Result.ok();
    }

    /**
     * 更换头像地址
     */
    @ApiOperation("更换头像地址")
    @PutMapping("/updateAvatar/{id}")
    public Result updateAvatar(@PathVariable("id") String id, HttpServletRequest httpServletRequest) {
        String avatar = httpServletRequest.getParameter("avatar");
        UcenterMember ucenterMember = new UcenterMember();
        ucenterMember.setId(id);
        ucenterMember.setAvatar(avatar);
        boolean result = memberService.updateById(ucenterMember);
        if (result) return Result.ok();
        return Result.error();
    }

    /**
     * 根据ID修改用户信息
     */
    @ApiOperation("根据ID修改用户信息")
    @PutMapping("/updateUcenterMemberById")
    public Result updateUcenterMemberById(@RequestBody UcenterMember ucenterMember) {
        boolean result = memberService.updateById(ucenterMember);
        if (result) return Result.ok();
        return Result.error();
    }

    /**
     * 根据比赛ID查询玩家比赛信息
     *
     * @param contestId 参与比赛ID
     * @return
     */
    @ApiOperation("根据比赛ID查询玩家比赛信息")
    @GetMapping("/getParameter/{contestId}")
    public Result getParameterByContestId(@PathVariable("contestId") String contestId) {
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("is_parameter", contestId);
        List<UcenterMember> ucenterMemberList = memberService.list(wrapper);
        return Result.ok().data("items", ucenterMemberList);
    }


}


